package com.gx.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gx.server.common.BaseResponse;
import com.gx.server.common.ErrorCode;
import com.gx.server.common.ResultUtils;
import com.gx.server.model.domain.Membership;
import com.gx.server.model.domain.User;
import com.gx.server.model.service.MembershipService;
import com.gx.server.model.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @author Dobby
 * @version 1.0
 */

@RestController
@RequestMapping("/Membership")
@Slf4j
public class MembershipController {

    @Autowired
    MembershipService membershipService;


    /**
     * 购买会员
     * @param user_id
     * @return
     */
    @PostMapping("/buy")
    public BaseResponse<String> buy_vip(@RequestParam Long user_id, @RequestParam int day) {
        Membership membership = new Membership();

        LambdaQueryWrapper<Membership> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Membership::getUserId,user_id);
        Membership one = membershipService.getOne(queryWrapper);

        //如果购买过，那么返回他的购买到期时间
        if (one!=null){
            return ResultUtils.error(ErrorCode.FORBIDDEN,one.getEndDate().toString(),"购买失败");
        }

        membership.setUserId(user_id);

        LocalDateTime now = LocalDateTime.now();
        membership.setStartDate(now);
        LocalDateTime end = now.plusDays(day);// 在当前日期和时间上添加30天
        membership.setEndDate(end);
        boolean save = membershipService.save(membership);

        if (save){
            return ResultUtils.success("购买成功");
        }else {
            return ResultUtils.error(ErrorCode.FORBIDDEN,"购买失败");
        }

    }
}
